# Name: JoinLakeGrid.py - MCBS 10/20/2014
# Description: Joins Lakes to grid and saves table

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridName      = "G1kmMiR"
# Output grids name:
OutName       = "G1kmMiRLake"

JoinClass       = "Lake" 
OutputFeature   = OutName
fieldmappings   = arcpy.FieldMappings()
fieldmappings.addTable(GridName)
arcpy.SpatialJoin_analysis(GridName, JoinClass, OutputFeature,
						   "JOIN_ONE_TO_MANY", "KEEP_ALL", fieldmappings,
						   "COMPLETELY_WITHIN", "", "")
print "Joining attributes from " + JoinClass + " to grid."
print "New Grid file containing attributes created: " + OutputFeature
print " "
# Save .dbf tables in specified folder
TableName    = OutputFeature + ".dbf"
arcpy.TableToTable_conversion(OutputFeature, PathForTables, TableName)


# # Export table as .csv:
# import win32com.client

# # Define excel
# excel = win32com.client.Dispatch('Excel.Application')

# # Folder to store tables:

# TableName = OutName
# TableNameDbf = TableName + ".dbf"
# TableNameCsv = TableName + ".csv"

# InputDBF         = PathForTablesExcel + TableNameDbf
# OutputCSV        = PathForTablesExcel + TableNameCsv

# # Convert .dbf tables into .csv using excel.
# workbook     = excel.Workbooks.Open(InputDBF)
# workbook.SaveAs(OutputCSV,FileFormat=24)
# print "Output table saved: " + TableNameCsv
# print " "

# excel.Quit()
